<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load=""
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel"
        >

      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import { getListData } from '@/api/workorder/workorderreport'
import { mapGetters } from 'vuex'

export default {
  name: 'reportData',
  props:{
    docNo:{//工单
      type:String
    },
    workshopName:{//车间
      type:String
    },
    productLineName:{//产线
      type:String
    },
    itemCode:{//品号
      type:String
    },
    processId:{//工序ID
      type:String
    },
  },
  data() {
    return {
      searchForm: {},
      tableData: [],
      tableLoading: false,
      tableOption :{
        labelPosition: "right",
        labelSuffix: "：",
        labelWidth: 130,
        gutter: 0,
        menuBtn: true,
        submitBtn: true,
        submitText: "提交",
        emptyBtn: true,
        menuPosition: "center",
        border: true,
        index: true,
        indexLabel: "序号",
        stripe: true,
        menuAlign: "center",
        align: "center",
        searchMenuSpan:24,
        cellBtn:true,
        menuWidth:100,
        searchEnter: true,
        menu: false,
        addBtn: false,
        refreshBtn:false,
        columnBtn:false,
        height: '45vh',
        column: [
          {
            type: "input",
            label: "工单号",
            prop: "docNo",
            span: 12,
            overHidden:true,
          },
          {
            type: "input",
            label: "品号",
            prop: "itemCode",
            span: 12,
            overHidden:true,
          },
          {
            type: "input",
            label: "车间",
            prop: "workshopName",
            span: 12,
            overHidden:true,
          },
          {
            type: "input",
            label: "产线",
            prop: "productLineName",
            span: 12,
            overHidden:true,
          },
          {
            type: "input",
            label: "流程图号",
            prop: "flowChartNo",
            span: 12,
            overHidden:true,
          },
   /*       {
            type: "input",
            label: "工位",
            prop: "workPositionName",
            span: 12,
            overHidden:true,
          },*/
          {
            type: "input",
            label: "工段",
            prop: "workshopSection",
            span: 12,
            overHidden:true,
          },
          {
            type: "input",
            label: "工序",
            prop: "processName",
            span: 12,
            overHidden:true,
          },
          {
            type: "input",
            label: "产品类型",
            prop: "productLineType",
            overHidden:true,
          },
          {
            type: "input",
            label: "在制品完成数量",
            prop: "workInProgressQty",
            span: 12,
            width: 110,
          },
          {
            type: "input",
            label: "在制品报废数量",
            prop: "workInProgressScrapQty",
            span: 12,
            width: 110,
          },
          {
            type: "input",
            label: "不良数量",
            prop: "badQty",
            span: 12,
            width: 80,
          },
          {
            type: "input",
            label: "返工数量",
            prop: "reworkQty",
            span: 12,
            width: 80,
          },
    /*      {
            type: "select",
            label: "工位状态",
            prop: "moStatus",
            overHidden:true,
            span: 12,
            html:true,//配置html设置为true即可支持formatter转义html代码
            dicData:[
              {
                label:'未完工',
                value:'未完工'
              },{
                label:'已完工',
                value:'已完工'
              }
            ],
            formatter:(val) => {
              if( val.moStatus=='未完工') {
                return '<b style="color:red">未完工</b>'
              }else if(val.moStatus=='已完工'){
                return '<b style="color:green">已完工</b>'
              }
            },
            cell: true,
          },*/
          {
            type: "input",
            label: "报工时间",
            prop: "reportTime",
            span: 12,
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            overHidden:true,
          },
          {
            type: "input",
            label: "报工人",
            prop: "reportBy",
            span: 12,
            overHidden:true,
          },
        ],
      },
      spans: {}

    }
  },
  watch: {
    tableData: {
      handler(newVal) {
        this.calculateSpans();
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.workorder_workorderreport_add, false),
        delBtn: this.vaildData(this.permissions.workorder_workorderreport_del, false),
        editBtn: this.vaildData(this.permissions.workorder_workorderreport_edit, false)
      }
    }
  },
  created() {
    this.calculateSpans();
  },
  methods: {
    // 列表查询
    getList(page, params) {
      this.tableLoading = true
      if(!this.validatenull(this.docNo)){
        this.searchForm.docNo = this.docNo;
      }
      if(!this.validatenull(this.workshopName)){
        this.searchForm.workshopName = this.workshopName;
      }
      if(!this.validatenull(this.productLineName)){
        this.searchForm.productLineName = this.productLineName;
      }
      if(!this.validatenull(this.itemCode)){
        this.searchForm.itemCode = this.itemCode;
      }
      if(!this.validatenull(this.processId)){
        this.searchForm.processId = this.processId;
      }
      getListData(this.searchForm).then(response => {
        this.tableData = response.data.data
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 删除
    handleDel: function(row, index) {
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    // 更新
    handleUpdate: function(row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 保存
    handleSave: function(row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page)
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile('/workorder/workorderreport/export', this.searchForm, 'workorderreport.xlsx')
    },
    calculateSpans() {
      const columns = this.tableOption.column; // 获取表格列配置
      this.spans = {}; // 初始化 spans 对象，用于存储每列的合并信息
      columns.forEach(column => { // 遍历每一列
        const prop = column.prop || column.property; // 获取列的属性名（prop 或 property）
        this.spans[prop] = this.rowSpan(prop); // 计算该列的合并信息，并存储在 spans 对象中
      });
    },
    rowSpan(prop) {
      let list = []; // 初始化一个数组，用于存储每行的合并信息
      let position = 0; // 初始化位置指针，用于记录当前合并段的起始位置
      this.tableData.forEach((item, index) => { // 遍历表格数据
        if (index === 0) {
          list.push(1); // 第一行默认合并值为1
        } else {
          if (this.tableData[index][prop] === this.tableData[index - 1][prop]) {
            list[position] += 1; // 如果当前行与前一行相同，则增加合并值
            list.push(0); // 当前行被合并，设置为0
          } else {
            list.push(1); // 如果不同，则当前行不合并，设置为1
            position = index; // 更新位置指针到当前行
          }
        }
      });
      return list; // 返回合并信息列表
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      // 定义不需要合并的列的属性名
      const noMergeColumns = ['workInProgressQty', 'workInProgressScrapQty', 'reworkQty', 'moStatus', 'reportTime','reportBy'];
      console.log(column);
      // 排除操作列和序号列
      if (column.label === '操作'  || column.type === 'index' || columnIndex===16) {
        return {
          rowspan: 1,
          colspan: 1
        };
      }

      // 获取当前列的属性名
      const prop = column.prop || column.property;

      // 如果当前列在不需要合并的列范围内，则不进行合并
      if (noMergeColumns.includes(prop)) {
        return {
          rowspan: 1,
          colspan: 1
        };
      }

      // 继续执行原有的合并逻辑
      if (this.spans[prop]) {
        const _row = this.spans[prop][rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      return {};
    },
  }
}
</script>

<style scoped>
/deep/ .avue-crud__menu {
  min-height: 0px!important;
}
/deep/.el-card__body, .el-main{
  padding: 0px!important;
}
</style>

